package com.hnx.admin.aurora.system.service.impl;

import com.google.code.kaptcha.Producer;
import com.hnx.admin.aurora.captcha.api.CaptchaAPI;
import com.hnx.admin.aurora.captcha.config.KatchaConfig;
import com.hnx.admin.aurora.redis.RedisCache;
import com.hnx.admin.aurora.system.domain.param.user.query.LoginQuery;
import com.hnx.admin.aurora.system.service.CaptchaService;
import com.hnx.admin.aurora.system.service.SysConfigService;
import com.hnx.admin.aurora.web.json.ResultJson;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintValidatorContext;
import java.util.UUID;

/*
创建人： 倔强的头发
创建时间：2025/6/14
功能描述:

*/
@Service
@RequiredArgsConstructor
public class CaptchaServiceImpl implements CaptchaService, CaptchaAPI {
    private final KatchaConfig katchaConfig;
    private final Producer producer;
    private final RedisCache redisCache;
    private final SysConfigService sysConfigService;

    @Override
    public ResultJson getCode(HttpServletResponse response) {
        String uuid = UUID.randomUUID().toString().replace("-","");
        String code = katchaConfig.createCode(producer,uuid);
        return ResultJson.success().add("uuid", uuid).add("img",code);
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        boolean captchaEnabled = sysConfigService.selectCaptchaEnabled();
        if (captchaEnabled) {
            if(value instanceof LoginQuery){
                LoginQuery userQuery = (LoginQuery) value;
                if(!StringUtils.hasText(userQuery.getCode())){
                    valid(context,CAPTCHA_NONE);
                    return false;
                }
                String verifyKey = captchaKey(userQuery.getUuid());
                String captcha = redisCache.getCacheObject(verifyKey, String.class);
                if (org.apache.commons.lang3.StringUtils.isBlank(captcha)) {
                    valid(context,CAPTCHA_EXPIRE);
                    return false;
                }
                if (!captcha.equalsIgnoreCase(userQuery.getCode())) {
                    redisCache.deleteObject(verifyKey);
                    valid(context,CAPTCHA_ERROR);
                    return false;
                }
            }
        }
        return true;
    }
}
